package com.scarecrow.blit2d.core {
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	
	/**
	 * Canvas for blitting a full scene. This is the root for any blitted display tree.
	 * ...
	 * @author Santiago.J.Elizalde
	 */
	public class BlitCanvas extends Sprite {
		
		private var screenDisplay:Bitmap;
		private var screenBuffer:BitmapData;
		
		private var registeredComponents:Array;
		private var sorter:IDisplaySorter;
		
		private var gutter:uint;
		
		public function BlitCanvas(gutterSize:int) {
			
			gutter = gutterSize;
			addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
		}
		
		private function onAddedToStage(e:Event):void {
			removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			
			screenBuffer = new BitmapData(parent.width, parent.height, true, 0x00000000);
			regenerateDisplay();
		}
		
		private function regenerateDisplay():void {
			if (screenDisplay.parent) screenDisplay.parent.removeChild(screenDisplay);
			screenDisplay = new Bitmap(null, "auto", false);
			screenDisplay.bitmapData = screenBuffer;
			addChild(screenDisplay);
		}
		
		public function addDisplayComponent(component:IDisplayRenderer):void {
			registeredComponents.push(component);
		}
		
		public function removeDisplayComponent(component:IDisplayRenderer):void {
			var objectIndex:int = registeredComponents.indexOf(component);
			if (objectIndex > -1) {
				registeredComponents.splice(objectIndex, 1);
			}
		}
		
		/**
		 * Renders the scene, copying the bimaps of all registered renderers onto the canvas.
		 */
		public function render():void {
			
			var componentsSorted:Array = sorter.sort(registeredComponents);
			screenBuffer.fillRect(screenBuffer.rect, 0x00000000);
			for each (var item:IDisplayRenderer in componentsSorted) {
				if (!item.visible) continue;
				screenBuffer.copyPixels(item.displayData, item.displayData.rect, item.drawPosition, null, null, true);
			}
		}
	}

}